package handler

import (
	"net/http"

	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/dto"
	"gitee.com/hp-huiw/family-expense-api/internal/service"
	"github.com/gin-gonic/gin"
)

type AccountGroupHandler interface {
	QueryAccountGroupInfo(ctx *gin.Context)
	QueryBasicStatistics(ctx *gin.Context)
	Update(ctx *gin.Context)
}

func NewAccountGroupHandler(db *sql.DB) AccountGroupHandler {
	return &accountGroupHandler{
		accountGroupService: service.NewAccountGroupService(db),
	}
}

// Matches /query-account-group-info of http get action.
func (h *accountGroupHandler) QueryAccountGroupInfo(ctx *gin.Context) {
	c := ctx.Request.Context()
	claims := GetClaims(ctx)
	accountGroupID := claims.AccountGroupID
	userID := claims.UserID
	result, err := h.accountGroupService.QueryInfo(c, accountGroupID, userID)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendDataResponse(ctx, result)
}

// Matches /query-basic-statistics of http get action.
func (*accountGroupHandler) QueryBasicStatistics(ctx *gin.Context) {
	c := ctx.Request.Context()
	db := GetDatabase(ctx)
	accountGroupID := GetClaims(ctx).AccountGroupID
	result, err := service.NewIncomeExpenseDetailService(db).QueryBasicStatistics(c, accountGroupID)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendDataResponse(ctx, result)
}

// Matches /update of http post action.
func (h *accountGroupHandler) Update(ctx *gin.Context) {
	postedData := dto.AccountGroupRequest{}

	if err := ctx.ShouldBindJSON(&postedData); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()

	if err := h.accountGroupService.Update(c, &postedData); err != nil {
		ctx.Error(err)
		return
	}

	SendStatusResponse(ctx, http.StatusNoContent)
}

// Container of AccountGroupHandler functions.
type accountGroupHandler struct {
	accountGroupService service.AccountGroupService
}
